package com.heima.test;

import com.alibaba.fastjson.JSON;
import com.heima.ArticleApp;
import com.heima.article.entity.ApArticle;
import com.heima.article.service.IApArticleService;
import com.heima.search.entity.ApArticleSearch;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author: itheima
 * @create: 2022-07-12 10:35
 */
@SpringBootTest(classes = ArticleApp.class)
@RunWith(SpringRunner.class)
public class BatchImportES {

    @Autowired
    private RestHighLevelClient restHighLevelClient;


    @Autowired
    private IApArticleService articleService;


    @Test
    public void importData2ES() throws IOException {
        //1.根据条件查询文章列表
        List<ApArticle> list = articleService.list();

        //2.构建文章索引库对象 将数据批量写入到ES索引库
        List<ApArticleSearch> collect = list.stream().map(apArticle -> {
            ApArticleSearch apArticleSearch = new ApArticleSearch();
            BeanUtils.copyProperties(apArticle, apArticleSearch);
            return apArticleSearch;
        }).collect(Collectors.toList());

        //2.1 构建批量操作请求对象
        BulkRequest bulkRequest = new BulkRequest();

        //2.2 遍历文档集合 加入批量操作对象
        for (ApArticleSearch apArticleSearch : collect) {
            bulkRequest.add(new IndexRequest("app_info_article").id(apArticleSearch.getId().toString()).source(JSON.toJSONString(apArticleSearch), XContentType.JSON));
        }

        //2.3 执行新增
        BulkResponse responses = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
        System.out.println(responses);

    }
}
